package com.manor.main.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.manor.common.CommonAppContext;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.http.JHttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.ActivityManager;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.R;
import com.manor.main.custom.CalendarView;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpUtil;
import com.manor.main.login.VCodeVerifyFragment;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * 注册填写资料
 */
@Route(path = RouteUtil.PC_INPUT_GENDER)
public class LoginGenderAgeActivity extends BaseLocationActivity implements View.OnClickListener {

    private TextView mTvGenderNan;
    private TextView mTvGenderNv;
    private CalendarView mWheelYear;
    private CalendarView mWheelMonth;
    private CalendarView mWheelDay;
    private TextView mTvGotoMain;
    private LinearLayout mllNv;
    private LinearLayout mllNan;
    private ImageView mIvNan;
    private ImageView mIvNv;
    private TextView tv_getcode;
    private EditText ed_code;

    private String years = "2020", months = "01", days = "01";
    //定义滚动选择器的数据项（年月日的）
    ArrayList<String> gradeYear = new ArrayList<>();
    ArrayList<String> gradeMonth = new ArrayList<>();
    ArrayList<String> gradeDay = new ArrayList<>();
    private int genderType = 0; //1男 2女

    @Override
    protected void main() {
        super.main();
        initView();
        myCalendar();
        handleIntent(getIntent());

    }

    private void handleIntent(Intent intent) {
        if (intent != null) {
            if (intent.hasExtra(FROM_TYPE)) {
                fromType = intent.getIntExtra(FROM_TYPE, 0);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

    private void myCalendar() {


        //为数据项赋值
        @SuppressLint("SimpleDateFormat")
        int thisYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new java.util.Date())) - 16;
        for (int i = 1920; i <= thisYear; i++) //从1980到今年
        {
            gradeYear.add(i + "");
        }
        for (int i = 1; i <= 12; i++) {
            // 1月到12月
            if (i < 10) {
                gradeMonth.add("0" + i + "");
            } else {
                gradeMonth.add(i + "");
            }
        }
        for (int i = 1; i <= 31; i++) {          // 1日到31日
            if (i < 10) {
                gradeDay.add("0" + i);
            } else {
                gradeDay.add(i + "");
            }
        }


        //为滚动选择器设置数据
        mWheelYear.setData(gradeYear);
        mWheelMonth.setData(gradeMonth);
        mWheelDay.setData(gradeDay);
        //开启震动反馈
        mWheelYear.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
        mWheelMonth.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
        mWheelDay.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);

        mWheelYear.setSelected(thisYear - 1920);
        mWheelMonth.setSelected(0);
        mWheelDay.setSelected(0);
        years = thisYear + "";

        //滚动选择事件
        mWheelYear.setOnSelectListener(new CalendarView.onSelectListener() {
            @Override
            public void onSelect(String data) {
                years = data;
                setCaledarDate();
            }
        });
        mWheelMonth.setOnSelectListener(new CalendarView.onSelectListener() {
            @Override
            public void onSelect(String data) {
                months = data;
                setCaledarDate();
            }
        });
        mWheelDay.setOnSelectListener(new CalendarView.onSelectListener() {
            @Override
            public void onSelect(String data) {
                days = data;
                //                setCaledarDate();
            }
        });


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_gender_age;
    }

    public void setCaledarDate() {
        int monthss = Integer.parseInt(months);
        if ((monthss == 1) || (monthss == 3) || (monthss == 5) || (monthss == 7) || (monthss == 8) || (monthss == 10) || (monthss == 12)) {
            if (gradeDay.size() > 0) {
                gradeDay.clear();
            }
            for (int j = 1; j <= 31; j++) {
                if (j < 10) {
                    gradeDay.add("0" + j);
                } else {
                    gradeDay.add(j + "");
                }


            }
        } else if ((monthss == 4) || (monthss == 6) || (monthss == 9) || (monthss == 11)) {
            if (gradeDay.size() > 0) {
                gradeDay.clear();
            }
            for (int j = 1; j <= 30; j++) {
                if (j < 10) {
                    gradeDay.add("0" + j);
                } else {
                    gradeDay.add(j + "");
                }
            }
        } else {
            //判断是不是闰年
            int year = Integer.parseInt(years);
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                //29天
                if (gradeDay.size() > 0) {
                    gradeDay.clear();
                }
                for (int j = 1; j <= 29; j++) {
                    if (j < 10) {
                        gradeDay.add("0" + j);
                    } else {
                        gradeDay.add(j + "");
                    }
                }
            } else {
                //28天
                if (gradeDay.size() > 0) {
                    gradeDay.clear();
                }
                for (int j = 1; j <= 28; j++) {
                    if (j < 10) {
                        gradeDay.add("0" + j);
                    } else {
                        gradeDay.add(j + "");
                    }
                }

            }
        }
        mWheelDay.setData(gradeDay);
        mWheelDay.setSelected(0);
    }

    private void initView() {
        mTvGenderNan = findViewById(R.id.tv_gender_nan);
        mTvGenderNv = findViewById(R.id.tv_gender_nv);
        mWheelYear = findViewById(R.id.wheel_year);
        mWheelMonth = findViewById(R.id.wheel_month);
        ed_code = findViewById(R.id.ed_code);
        mWheelDay = findViewById(R.id.wheel_day);
        mTvGotoMain = findViewById(R.id.tv_goto_main);
        mllNv = findViewById(R.id.ll_nv);
        mllNan = findViewById(R.id.ll_nan);
        mIvNan = findViewById(R.id.iv_nan);
        mIvNv = findViewById(R.id.iv_nv);
        tv_getcode = findViewById(R.id.tv_getcode);
        mTvGotoMain.setOnClickListener(this);
        mllNan.setOnClickListener(this);
        mllNv.setOnClickListener(this);
        tv_getcode.setOnClickListener(this);
        if (!parentSdNo.equals("")) {
            ed_code.setText(parentSdNo + "");
            ed_code.setFocusable(false);
            ed_code.setFocusableInTouchMode(false);
            tv_getcode.setVisibility(View.INVISIBLE);
        }

    }

    public static final String FROM_TYPE = "fromType";
    private int fromType;

    /**
     * @param fromType 0-首页             跳转到新的注册登录
     *                 1-注册             跳转到新的注册登录
     *                 2-验证码登录        跳转到验证码登录
     */
    public static void forward(int fromType) {
        Intent intent = new Intent(CommonAppContext.sInstance, LoginGenderAgeActivity.class);
        intent.putExtra(FROM_TYPE, fromType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        CommonAppContext.sInstance.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_nan) {

            mIvNan.setImageDrawable(getDrawable(R.mipmap.gender_selected));
            mIvNv.setImageDrawable(getDrawable(R.mipmap.gender_select));
            genderType = 1;

        } else if (v.getId() == R.id.ll_nv) {

            mIvNan.setImageDrawable(getDrawable(R.mipmap.gender_select));
            mIvNv.setImageDrawable(getDrawable(R.mipmap.gender_selected));
            genderType = 2;

        } else if (v.getId() == R.id.tv_goto_main) {

            if (ClickUtil.canClick(1000)) {
                if (genderType == 1) {
                    showTip("提示", "你当前选择性别 男，性别选择错误无法更改", () -> {
                        startMain();
                    });
                } else {
                    showTip("提示", "你当前选择性别 女，性别选择错误无法更改", () -> {
                        startMain();
                    });
                }


            }
        } else if (v.getId() == R.id.tv_getcode) {
            new XPopup.Builder(mContext)
                    .asConfirm(null, "是否没有邀请人，确认后无法修改", "取消", "确定", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            JMainHttpUtil.getInvitationCode(new JHttpCallback() {
                                @Override
                                public void onSuccess(int code, String msg, String info) {
                                    if (code == 200) {
                                        //  StringDataBean stringDataBean = GsonUtil.gsonToBean(info,StringDataBean.class);
                                        ed_code.setText(info + "");
                                    }
                                }

                                @Override
                                public void onError() {
                                    super.onError();

                                }
                            });
                        }
                    }, null, false).show();
        }
    }

    private void showTip(String title, String content, OnConfirmListener confirmListener) {
        new XPopup.Builder(mContext)
                .asConfirm(title, content, "取消", "确定", confirmListener, null, false).show();
    }

    int sun = 0;
    private final Handler handler = new Handler() {
        //接收handler发送的message
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            startMain();
        }
    };


    private void startMain() {
        if (genderType == 0) {
            ToastUtil.show("请选择性别");
            return;
        }
        if (TextUtils.isEmpty(ed_code.getText())) {
            ToastUtil.show("请输入邀请码");
            return;
        }
        String date = years + "-" + months + "-" + days;

        String[] uidAndToken = SpUtil.getInstance().getMultiStringValue(
                SpUtil.UID, SpUtil.TOKEN);
        final String uid = uidAndToken[0];
        final String token = uidAndToken[1];
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {
            mTvGotoMain.setAlpha(0.6f);
            mTvGotoMain.setClickable(false);
            Logger.i("uid---" + uid + "token---" + token);

            if (npcCode == 0) {
                showWaitingDialog(false);
                if (sun >= 3) {
                    // ToastUtil.show("无法获取您的位置，请走到开阔地带重试");
                    dismissWaitingDialog();
                    sun = 0;
                } else {
                    handler.sendEmptyMessageDelayed(0, 1000);//发送消息
                    sun++;
                    return;
                }
            } else {
                dismissWaitingDialog();
            }

            showWaitingDialog(false);
            getLocation(new ILocationResultListener() {
                @Override
                public void onSuccess(int cityCode) {
                    JMainHttpUtil.updateAvatar(uid, token, genderType, date, cityCode, ed_code.getText().toString(), new JHttpCallback() {
                        @Override
                        public void onError() {
                            super.onError();
                            dismissWaitingDialog();
                            mTvGotoMain.setClickable(true);
                            mTvGotoMain.setAlpha(1f);
                        }

                        @Override
                        public void onSuccess(int code, String msg, String info) {
                            dismissWaitingDialog();
                            if (code == 200) {
                                getBaseUserInfo();
                            } else {
                                ToastUtil.show(msg);
                                mTvGotoMain.setClickable(true);
                                mTvGotoMain.setAlpha(1f);
                            }
                        }
                    });
                }
            });
        } else {
            if (fromType == 2) {
                OtherPhoneLoginActivity.forward();
            } else {
                finish();
                ARouter.getInstance()
                        .build(RouteUtil.PATH_LOGIN)
                        .withInt(VCodeVerifyFragment.FLAG_FROM_TYPE, 0)
                        .navigation();
            }
        }
    }


    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                if (bean != null) {
                    MainActivity.Companion.forward(mContext, false);
                    ActivityManager.getInstance().finishOtherActivities(LoginGenderAgeActivity.class, false);
                    finish();
                } else {
                    mTvGotoMain.setClickable(true);
                    mTvGotoMain.setAlpha(1f);
                }
            }
        });
    }
}
